<script setup lang="ts">
import { ref, onMounted } from "vue";
import { formRules } from "./utils/rule";
import { FormProps } from "./utils/types";
import type { FormInstance } from "element-plus";
import { pro_cate_list, pro_list } from "@/api/product";

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    deal_log_id: "",
    id: "",
    table_at: "",
    version: "",
    product_json: [],
    price: ""
  })
});

const ruleFormRef = ref<FormInstance>();
const newFormInline = ref(props.formInline);

const goodSearchList = ref([]);

onMounted(() => {
  getProCateListFn();
});

function removeEmptyChildren(array) {
  return array.filter(item => {
    // 如果 children 存在且不为空数组，则保留该元素
    if (item.children && item.children.length > 0) {
      // 递归处理子元素
      item.children = removeEmptyChildren(item.children);
      return true;
    }
    // 如果没有 children 属性或者 children 为空数组，则保留该元素
    return !item.hasOwnProperty('children');
  });
}

// 获取产品分类及列表
function getProCateListFn() {
  pro_cate_list({
    page: 1,
    pagesize: 999
  }).then(res => {
    let cateList = res.data;
    pro_list({
      page: 1,
      pagesize: 9999
    }).then(res => {
      let goodList = res.data;
      for (let i = 0; i < cateList.length; i++) {
        cateList[i].children = [];
        for (let j = 0; j < goodList.length; j++) {
          if (goodList[j].cateId == cateList[i].id) {
            cateList[i].children.push(goodList[j]);
          }
        }
      }
      goodSearchList.value = removeEmptyChildren(cateList);
    });
  });
}

function getRef() {
  return ruleFormRef.value;
}

defineExpose({ getRef });
</script>

<template>
  <div>
    <el-form
      ref="ruleFormRef"
      :rules="formRules"
      :model="newFormInline"
      label-position="top"
    >
      <el-form-item label="成交产品" prop="product_json">
        <el-cascader
          v-model="newFormInline.product_json"
          class="w-full!"
          placeholder="请选择"
          :options="goodSearchList"
          :props="{ value: 'id', label: 'name' }"
          clearable
        />
      </el-form-item>
      <el-form-item label="金额" prop="price">
        <el-input
          type="number"
          v-model="newFormInline.price"
          placeholder="请输入"
          clearable
        >
          <template #append>元</template>
        </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>
